/**
 登录、获取用户信息、退出登录、清除accessToken逻辑，不建议修改
 */

import Vue from 'vue'
import { getUserInfo, login, logout } from '@/api/user'
import {cooperate} from '@/api/cooperate'
import VueRouter from 'vue-router'
import {
  getAccessToken,
  removeAccessToken,
  setAccessToken,
} from '@/utils/accessToken'
import { resetRouter } from '@/router'
import { title, tokenName } from '@/config'

const state = {
  accessToken: getAccessToken(),
  username: window.sessionStorage.getItem('username'),
  avatar: '',
  permissions: []
}
const getters = {
  accessToken: (state) => state.accessToken,
  username: (state) => state.username,
  avatar: (state) => state.avatar,
  permissions: (state) => state.permissions,
}
const mutations = {
  setAccessToken(state, accessToken) {
    let token = accessToken
    state.accessToken = accessToken
    setAccessToken(token)
  },
  setUsername(state, username) {
    state.username = username
  },
  setAvatar(state, avatar) {
    state.avatar = avatar
  },
  setPermissions(state, permissions) {
    state.permissions = permissions
  },
  setTel(state,tel){
    state.tel = tel
  }
}
const actions = {
  setPermissions({ commit }, permissions) {
    commit('setPermissions', permissions)
  },
  async login({ commit }, userInfo) {
    const { data } = await login(userInfo)
    console.log(data)
    const accessToken = data.token
    if (accessToken) {
      commit('setAccessToken', accessToken)
    } else {

    }
  },
  //入驻平台
  async Enterlogin({ commit }, userInfo){
    const { data } = await cooperate(userInfo)
    const accessToken = data.token
    if (accessToken) {
      commit('setAccessToken', accessToken)
      Vue.prototype.$baseMessage('恭喜您入驻成功！', 'success')

      window.location.href = '/'
    } else {

    }
  },
  async getUserInfo({ commit, state }) {
    const { data } = await getUserInfo(state.accessToken)
    if (!data) {
      Vue.prototype.$baseMessage('验证失败，请重新登录...', 'error')
      return false
    }
    let { button, nickname } = data
    if (button && nickname && Array.isArray(button)) {
      commit('setPermissions', button)
      commit('setUsername', nickname)
      window.sessionStorage.setItem('issetpassword',false)
      window.sessionStorage.setItem('username',nickname)
      window.sessionStorage.setItem('permissions',JSON.stringify(button))

      window.sessionStorage.setItem('userinfo',JSON.stringify(data))
      return button
    } else {
      Vue.prototype.$baseMessage('用户信息接口异常', 'error')
      return false
    }
  },
  async logout({ dispatch }) {
    await logout(state.accessToken)
    await dispatch('resetAccessToken')
    await resetRouter()
  },
  resetAccessToken({ commit }) {
    commit('setPermissions', [])
    commit('setAccessToken', '')
    //清空用户名
    window.sessionStorage.removeItem('username')
    //清空数据是否显示认证弹窗
    window.sessionStorage.removeItem('isauth')
    removeAccessToken()
  },
}
export default { state, getters, mutations, actions }
